//
//  ConsultDoctorsViewController.m
//  安好
//
//  Created by lianchuang on 14/11/12.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "ConsultDoctorsViewController.h"
#import "DepartmentTableViewCell.h"
#import "ConsultDocListViewController.h"
#import "SpecifyDoctorManager.h"
@interface ConsultDoctorsViewController ()<SpecifyDoctorManagerDelegate,UIAlertViewDelegate>

@end

@implementation ConsultDoctorsViewController
{
    NSDictionary *dicData;
    NSInteger page;
    NSInteger sel_count;
    NSInteger current_count;
}
- (void)viewWillAppear:(BOOL)animated
{
//    [[SpecifyDoctorManager instance] getAllSpecifyDoctors];
//    [[SpecifyDoctorManager instance] setDelegate:self];
    [self loadAssinDoctors];
}
- (void)didLoadAllSpecifyDoctors:(NSArray *)allSpecifyDoctors
{
    [self.dataArray removeAllObjects];
    NSDictionary *dic=@{        @"departmentid" :@"0",
                                @"departmentname": @"不确定科室",
                                @"username" : @"不指定医生",
                                @"uid":@"0",
                                @"avatar":@"",
                        };
    self.dataArray=[[NSMutableArray alloc]initWithObjects:dic, nil];

    if ([allSpecifyDoctors count]>0) {
        for(NSDictionary *dict in allSpecifyDoctors)
        {
            NSDictionary *d=@{
                              @"departmentid" :[dict valueForKey:@"departmentid"],
                              @"departmentname": [dict valueForKey:@"departmentname"],
                              @"username" : [dict valueForKey:@"doctorname"],
                              @"uid":[dict valueForKey:@"doctoruid"],
                              @"avatar":[dict valueForKey:@"avatar"]
                              };
            [self.dataArray addObject:d];
        }
        BOOL ishaveDoc=NO;
        for (int i=0; i<self.dataArray.count; i++) {
            NSString *uid=[NSString stringWithFormat:@"%@",[[self.dataArray objectAtIndex:i] valueForKey:@"uid"]];
            if ([self.uid isEqualToString:uid]) {
                ishaveDoc=YES;
                dicData=[self.dataArray objectAtIndex:i];
            }
        }
        if (!ishaveDoc) {
            self.uid=@"0";
        }
    }
    [self.tableview reloadData];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"指定医生";

//    SpecifyDoctorManager *spe=[SpecifyDoctorManager instance];
//    spe.delegate=self;
    self.dataArray=[[NSMutableArray alloc]init];
    self.tableview.dataSource=self;
    self.tableview.delegate=self;
    sel_count=0;
    current_count=0;
    self.tableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.tableview.frame=CGRectMake(0, 0,kScreenWidth , kScreenHeight-64);
    UIBarButtonItem *backImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    backImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backImg;
    self.automaticallyAdjustsScrollViewInsets = NO;
    dicData=[[NSDictionary alloc]init];
    page=0;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self hiddenActionView];
    if (self.docBlock) {
        //返回指定医生的个人信息
        self.docBlock(dicData);
    }

    
}
- (void)loadAssinDoctors
{
    NSString * getURL = [NSString stringWithFormat:@"%@question/myappoint/?platform=%@&version=%@&departmentid=%@&page=%@",kBaseURL,kPlatform,kVersion,self.departmentId,[NSString stringWithFormat:@"%ld",page+1]];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:getURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hiddenActionView];
        self.tableview.hidden=NO;
        MyNSLog("%@", responseObject);
        NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
        if ([status isEqualToString:@"1"])
        {
            [self.dataArray removeAllObjects];

            NSArray *array=[[NSMutableArray alloc]initWithArray:[responseObject valueForKey:@"data"]];
            for(NSDictionary *dict in array)
            {
                NSDictionary *d=@{
                                  @"departmentid" :[dict valueForKey:@"departmentid"],
                                  @"departmentname": [dict valueForKey:@"departmentname"],
                                  @"username" : [dict valueForKey:@"doctorname"],
                                  @"uid":[dict valueForKey:@"doctoruid"],
                                  @"avatar":[dict valueForKey:@"avatar"],
                                  @"isoutpatient":[NSString stringWithFormat:@"%@",[dict valueForKey:@"isoutpatient"]],
                                  @"doclevelid":[NSString stringWithFormat:@"%@",[dict valueForKey:@"doclevelid"]],
                                  };
                [self.dataArray addObject:d];

            }
            NSDictionary *dic=@{        @"departmentid" :@"0",
                                        @"departmentname": @"不确定科室",
                                        @"username" : @"不指定医生",
                                        @"uid":@"0",
                                        @"avatar":@"",
                                        @"isoutpatient":@"0",
                                        @"doclevelid":@"0"
                                        };
            [self.dataArray insertObject:dic atIndex:0];
            [self.tableview reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        self.tableview.hidden=NO;

    }];
}
//返回
- (void)backClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)returnDocData:(DoctorBlock)block
{
    self.docBlock=block;
}
#pragma mark TableviewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return self.dataArray.count;
    }else
    {
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifer=@"department";
    DepartmentTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:indentifer];
    if (cell==nil) {
        if (kScreenWidth==414) {
            cell=[[[NSBundle mainBundle] loadNibNamed:@"DepartmentTableViewCell" owner:self options:nil] lastObject];
        }else{
            cell=[[[NSBundle mainBundle] loadNibNamed:@"DepartmentTableViewCell" owner:self options:nil] objectAtIndex:0];
        }    }
    
    if (indexPath.section==0) {
        if (self.dataArray.count>0) {
            NSString *docname=[[self.dataArray objectAtIndex:indexPath.row] valueForKey:@"username"];
            cell.departmentName.text=[docname stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            if (indexPath.row==0) {
                cell.OutpatientLabel.text=@"";
            }else{
                NSString *isoutpatient=[NSString stringWithFormat:@"%@",[[self.dataArray objectAtIndex:indexPath.row] valueForKey:@"isoutpatient"]];
                if ([isoutpatient isEqualToString:@"0"]) {
                    cell.OutpatientLabel.text=@"（咨询时间外）";
                }else if([isoutpatient isEqualToString:@"1"])
                {
                    cell.OutpatientLabel.text=@"（咨询时间内）";
                }
            }
            if ([self.uid isEqualToString:[NSString stringWithFormat:@"%@",[[self.dataArray objectAtIndex:indexPath.row] valueForKey:@"uid"]]]) {
                cell.selectedImage.hidden=NO;
            }else
            {
                cell.selectedImage.hidden=YES;
            }
        }
    }else
    {
        cell.OutpatientLabel.text=@"";
        cell.departmentName.text=@"选择医生";
        cell.selectedImage.hidden=YES;
    }
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark TableviewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        

        current_count=indexPath.row;

        if (indexPath.row==0) {
            self.uid=[NSString stringWithFormat:@"%@",[[self.dataArray objectAtIndex:indexPath.row] valueForKey:@"uid"]];
            dicData=[self.dataArray objectAtIndex:indexPath.row];
            [self.tableview reloadData];
            DepartmentTableViewCell *cell=(DepartmentTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
            cell.selectedImage.hidden=NO;
        }else
        {
            NSString *isoutpatient=[NSString stringWithFormat:@"%@",[[self.dataArray objectAtIndex:indexPath.row] valueForKey:@"isoutpatient"]];
            
            if (![isoutpatient isEqualToString:@"1"]) {
                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"该医生不在咨询时间范围内，设为指定医生，可能无法及时回复您的咨询问题" delegate:self cancelButtonTitle:@"继续选择" otherButtonTitles:@"取消", nil];
                [alert show];
            }else{
                self.uid=[NSString stringWithFormat:@"%@",[[self.dataArray objectAtIndex:indexPath.row] valueForKey:@"uid"]];
                dicData=[self.dataArray objectAtIndex:indexPath.row];
                [self.tableview reloadData];
                DepartmentTableViewCell *cell=(DepartmentTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
                cell.selectedImage.hidden=NO;
            }
        }
    }
    else
    {
        ConsultDocListViewController *consultDoc=[[ConsultDocListViewController alloc]initWithNibName:@"ConsultDocListViewController" bundle:[NSBundle mainBundle]];
        consultDoc.departmentId=self.departmentId;
        consultDoc.isFromConsult=YES;
        [self.navigationController pushViewController:consultDoc animated:YES];
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        DepartmentTableViewCell *cell=(DepartmentTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        cell.selectedImage.hidden=YES;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (kScreenWidth==414) {
        return 53;
    }
    return 44.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 0;
    }
    return 10;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            self.uid=[NSString stringWithFormat:@"%@",[[self.dataArray objectAtIndex:current_count] valueForKey:@"uid"]];
            dicData=[self.dataArray objectAtIndex:current_count];
            sel_count=current_count;
            [self.tableview reloadData];
        }
        break;
        case 1:
        {
            self.uid=[NSString stringWithFormat:@"%@",[[self.dataArray objectAtIndex:sel_count] valueForKey:@"uid"]];
            dicData=[self.dataArray objectAtIndex:sel_count];
            [self.tableview reloadData];
        }
        break;
        default:
            break;
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
